package com.utilities;

import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.LineEvent.Type;


/**
 * @author xujsh(xjs250@163.com)
 *
 */
public class SimplePlayer {
	


	public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException, InterruptedException {
	
		playClip("/com/images/message.wav");
	}
	
	/*
	 * http://stackoverflow.com/questions/577724/trouble-playing-wav-in-java/577926#577926
	 */
	
	public static void playClip(String clipFile) throws IOException  {
	  class AudioListener implements LineListener {
	    private boolean done = false;
	    @Override public synchronized void update(LineEvent event) {
	      Type eventType = event.getType();
	      if (eventType == Type.STOP || eventType == Type.CLOSE) {
	        done = true;
	        notifyAll();
	      }
	    }
	    public synchronized void waitUntilDone() throws InterruptedException {
	      while (!done) { wait(); }
	    }
	  }
	  AudioListener listener = new AudioListener();
	  AudioInputStream audioInputStream = null;
	  try {
		   audioInputStream = AudioSystem.getAudioInputStream(
		          SimplePlayer.class.getResourceAsStream(clipFile));  //like :/com/creacker/message.wav
		    Clip clip = AudioSystem.getClip();
		    clip.addLineListener(listener);
		    clip.open(audioInputStream);
		    try {
		      clip.start();
		      listener.waitUntilDone();
		    } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
		      clip.close();
		    }
	  } catch (UnsupportedAudioFileException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (LineUnavailableException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
	    audioInputStream.close();
	  }
	}
}
